<?php

namespace App\Http\Service;

use App\Models\Comment;
use App\Models\Doubanpost;
use App\Models\Baoliaopost;
use App\Models\Commentvote;
use App\Http\Service\UserService;
use App\Http\Service\BaseService;



use Illuminate\Support\Facades\DB;
class CommentService  extends BaseService
{
    private $model;

    public function __construct(Comment $model,Commentvote $commentvote,Doubanpost  $doubanpost,UserService $userService,Baoliaopost $baoliaopost)
    {
        parent::__construct();
        $this->model = $model;
        $this->doubanpost=$doubanpost;
        $this->userService=$userService;
        $this->baoliaopost=$baoliaopost;
        $this->commentvote=$commentvote;
       
    }

    #统计某个帖子的数量
    public function totalComments($request,$data=[])
    {
        $type=$data['type'];
        $unique_id=$data['unique_id'];
        $where=[
            'unique_id'=>$unique_id,
            'type'=>$type,
        ];
        $count=$this->model->where($where)->count();
        if($type=='1'){
            //1  豆瓣评论(逛逛)
            $this->doubanpost->where(['unique_id'=>$unique_id])->update(['comment_count'=>$count]);
        }else{
            // 2. 爆料评论
            $this->baoliaopost->where(['unique_id'=>$unique_id])->update(['comment_count'=>$count]);

        }
        $where['people_id']=$data['people_id'];
        $num=$this->model->where($where)->count();
        $result=[
            'total_comments'=>$count,
            'total_comments_people'=>$num,
        ];
        return $result;
    }
    /**
     *
     * @param array $params
     * @return array
     */
    public function getList888($request,$data=[])
    {   
        //dd($request);
        $page = intval($request->input('page')) ?$request->input('page') :$this->cpage;
        $limit = intval($request->input('limit')) ?$request->input('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        $where = [
           ['status','=','1'],
        ];
        if(isset($data['type']) && !empty($data['type'])){
            $where[]=['type','=',$data['type']];
        }
        $fields = ['id','unique_id','parent_id','people_id','content','update_time','people_nickname','people_avatar','images','address','client_ip'];
        $data =$this->model->select($fields)
        ->where($where)
        ->orderBy('update_time', 'desc')
        ->orderBy('id', 'desc')
        ->get()->toArray();
        // 计算总数
        $count = count($data);
        $data =buildCategoryTree($data);

        $list= array_slice($data, $offset, $limit);
        $total_page=count($list);
        $result=[
            'page'=>$page,
            'limit'=>$limit,
            'count'=>$count,
            'total_page'=>$total_page,
            'data'=>$data,
        ];
        return $result;

    }
    //tohuto_msg
    public function tohuto_msg($people_id,$commented_people_id){
        $getUserData= $this->userService->getUserData();
        $result=[];

        if(isset($getUserData[$commented_people_id])&&isset($getUserData[$people_id])){
            $commenteduserData=$getUserData[$commented_people_id];
            $commented_nickname=$commenteduserData['nickname'];
            $userData=$getUserData[$people_id];
            $result['people_nickname']=$userData['nickname'];
            $result['people_avatar']=$userData['avatar'];
            $result['people_msg']="{$result['people_nickname']}回复{$commented_nickname}";
            $result['_people_msg']="{$commented_nickname}";


        }

        return $result;


    }
    public function getSonList($page = 1, $limit = 30, $parent_id,$data=[])
    {
        $commentvote_data=$this->check_status_list();
        $page = intval($page) ?$page:$this->cpage;
        $limit = intval($limit) ?$limit :$this->climit;
        $offset = ($page-1)*$limit;
        $sql="select count(1) as num from `module_comment`  where json_extract(crumbs, '$[1]') = {$parent_id} ";
        $count=DB::select($sql);
        $count=$count['0']->num;
        //$fields = ['id','unique_id','parent_id','people_id','content','update_time','commented_people_id','images','address','client_ip'];
/*        精彩和最新

        精彩=1：根据点赞数量排序，点赞高的在前

        最新=2：根据发布评论时间排序*/
        $status=$data['status'];
        //dd($status);
        if($status==1){
            $sql="select `id`,`unique_id`,`parent_id`,`people_id`,`content`,`update_time`,`commented_people_id`,`images`,`address` ,`client_ip`,`is_pubisher`,`like_count`,`dislike_count`    from `module_comment`  where json_extract(crumbs, '$[1]') = {$parent_id}  
            order by like_count desc 
            LIMIT {$offset}, {$limit} ";
        }else{
            $sql="select `id`,`unique_id`,`parent_id`,`people_id`,`content`,`update_time`,`commented_people_id`,`images`,`address` ,`client_ip`,`is_pubisher`,`like_count`,`dislike_count`     from `module_comment`  where json_extract(crumbs, '$[1]') = {$parent_id} 
             order by create_time desc

             LIMIT {$offset}, {$limit} ";
        }
        //die($sql);

        
        $list=DB::select($sql);
        $list = array_map('get_object_vars', $list);
        $user_id=$data['user_id'];

        //dd($user_id);
        foreach($list as &$v){
            $v['images']=json_decode($v['images'],true);
            $people_id=$v['people_id'];
            $commented_people_id=$v['commented_people_id'];
            $tohuto_msg=$this->tohuto_msg($people_id,$commented_people_id);
            if($tohuto_msg){
                $v['people_nickname']=$tohuto_msg['people_nickname'];
                $v['people_avatar']=$tohuto_msg['people_avatar'];
                $v['people_msg']=$tohuto_msg['people_msg'];
                $v['_people_msg']=$tohuto_msg['_people_msg'];
            }
            # 状态
            #判断状态
            $comment_id=$v['id'];
            //$comment_id=178;
            //dd($comment_id);
            $check_status=$this->check_status($commentvote_data,$comment_id,$user_id);
            $v['like_status']=$check_status['like_status'];
            $v['dislike_status']=$check_status['dislike_status'];



        }
        $total_page=count($list);

        $result=[
            'page'=>$page,
            'limit'=>$limit,
            'count'=>$count,
            'total_page'=>$total_page,
            'data'=>$list,
        ];
       // dd($result);
        return $result;
        
    }

    #查询列表
    public function check_status_list()
    {
        $fileds=['comment_id','user_id','vote_type'];
        $list=$this->commentvote->select($fileds)->get()->toArray();
        $result=[];
        if($list){
            foreach($list as $k=>$v){
                $key="{$v['user_id']}_{$v['comment_id']}";
                $result[$key]=$v;
            }
        }
        
        return $result;
    }

    #查询状态-列表展示
    public function  check_status($data,$comment_id,$user_id)
    {
        $key="{$user_id}_{$comment_id}";
        if(isset($data[$key])){
            $first=$data[$key];
        }else{
            $first=[];
        }
        //dd($first);

        $result=[];
        if($first){

            //dd($first);
            $vote_type=$first['vote_type'];
            switch ($vote_type) {
                case '1': # 点赞
                    $result=[
                        'like_status'=>'1',# 标红
                        'dislike_status'=>'2',#不标红
                    ];
                    break;
                case '-1': #点踩
                    $result=[
                        'like_status'=>'2',
                        'dislike_status'=>'1',
                    ];
                    break;
                case '2': #取消投票
                    $result=[
                        'like_status'=>'2',
                        'dislike_status'=>'2',
                    ];
                    break;
                default:
                    $result=[
                        'like_status'=>'2',
                        'dislike_status'=>'2',
                    ];
                    break;
            }

        }else{
                $result=[
                        'like_status'=>'2',
                        'dislike_status'=>'2',
                    ];
        }
        return $result;
    }


    public  function getList1($request,$data=[])
    {
        $commentvote_data=$this->check_status_list();
        //dd($commentvote_data);
        $page = intval($request->input('page')) ?$request->input('page') :$this->cpage;
        $limit = intval($request->input('limit')) ?$request->input('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        $where = [
           ['status','=','1'],
           ['parent_id','=','0'],
        ];

        if(isset($data['type']) && !empty($data['type'])){
            $where[]=['type','=',$data['type']];
        }
        if(isset($data['unique_id']) && !empty($data['unique_id'])){
            $where[]=['unique_id','=',$data['unique_id']];
        }
       // dd($where);
        // 计算总数
        $count = $this->model->where($where)->count();
        $fields = ['id','unique_id','parent_id','people_id','content','update_time','commented_people_id','images','address','client_ip','is_pubisher','like_count','dislike_count'];
        //$status=精彩=1   最新=2
/*        精彩：根据点赞数量排序，点赞高的在前
        最新：根据发布评论时间排序*/
        $status=$data['status'];
        //dd($status);
        if($status=='1'){
            $list=$this->model->where($where)->select()
            ->offset($offset)->limit($limit)
            ->orderBy('like_count', 'desc')
            ->get()->toArray();
        }else{
             $list=$this->model->where($where)->select()
            ->offset($offset)->limit($limit)
            ->orderBy('create_time', 'desc')
            ->get()->toArray();
        }
        $user_id=$data['user_id'];
        #dd($user_id);
        $getUserData= $this->userService->getUserData();
        foreach ($list as &$v) {
            $people_id=$v['people_id'];
            if(isset($getUserData[$people_id])){
                $userData=$getUserData[$people_id];
                $v['people_nickname']=$userData['nickname'];
                $v['people_avatar']=$userData['avatar'];
            }
            $v['images']=json_decode($v['images'],true); 
            $id=$v['id'];
            $v['son_num']=$this->model->where(['parent_id'=>$id])->count();

            #判断状态
            $comment_id=$v['id'];
            $check_status=$this->check_status($commentvote_data,$comment_id,$user_id);
            $v['like_status']=$check_status['like_status'];
            $v['dislike_status']=$check_status['dislike_status'];
            //dd($check_status);
           /// dd($v['son_num']);   
        }
        $total_page=count($list);
        $result=[
            'page'=>$page,
            'limit'=>$limit,
            'count'=>$count,
            'total_page'=>$total_page,
            'data'=>$list,
        ];
       // dd($result);
        return $result;

    }
    public  function getList2($request,$data=[])
    {
        $page= intval($request->input('page')) ?$request->input('page') :$this->cpage;
        $limit= intval($request->input('limit')) ?$request->input('limit') :$this->cpage;
        $id=$request->input("id");

        $getSonList=$this->getSonList($page,$limit,$id,$data);
        
        return $getSonList;

    }
    //select * from `module_comment`  where json_extract(crumbs, "$[1]") = 31
    public  function getList($request,$data=[])
    {
        $page = intval($request->input('page')) ?$request->input('page') :$this->cpage;
        $limit = intval($request->input('limit')) ?$request->input('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        $where = [
           ['status','=','1'],
           ['parent_id','=','0'],
        ];

        if(isset($data['type']) && !empty($data['type'])){
            $where[]=['type','=',$data['type']];
        }
        // 计算总数
        $count = $this->model->where($where)->count();
        $fields = ['id','unique_id','parent_id','people_id','content','update_time','commented_people_id','images','address','client_ip'];
        $list=$this->model->where($where)->select()
        ->offset($offset)->limit($limit)
        ->orderBy('update_time', 'desc')
        ->orderBy('id', 'desc')
        ->get()->toArray();
        $getUserData= $this->userService->getUserData();
        $pageson= intval($request->input('pageson')) ?$request->input('pageson') :$this->cpage;
        $limitson= intval($request->input('limitson')) ?$request->input('limitson') :$this->cpage;
        #状态
        $commentvote_data=$this->check_status_list();
        foreach ($list as &$v) {
            $v['images']=json_decode($v['images'],true);
            $people_id=$v['people_id'];
            if(isset($getUserData[$people_id])){
                $userData=$getUserData[$people_id];
                $v['people_nickname']=$userData['nickname'];
                $v['people_avatar']=$userData['avatar'];
            }
            $id=$v['id'];
            $getSonList=$this->getSonList($pageson,$limitson,$id);
            $data=$getSonList['data'];
            if(!empty($data)){
                $v['children']=$data;
            }else{
                $v['children']=[];
            }
            
        }
        $total_page=count($list);
        $result=[
            'page'=>$page,
            'limit'=>$limit,
            'count'=>$count,
            'total_page'=>$total_page,
            'data'=>$list,
        ];
       // dd($result);
        return $result;

        
    }
    public  function getCrumbs($pid = 0, &$ids = [])
    {
        $idArr = array_merge((array)$pid, $ids);
        $info = $this->model->where(['id'=> $pid])->first();
        if ($info['parent_id'] != 0) {
            $idArr = $this->getCrumbs($info['parent_id'], $idArr);
        } else {
            array_unshift($idArr, 0);
        }
        return $idArr;
    }
    /**
     * 一级评论添加
     * @param array $params
     * @return array
     */
    public function addDate1($request,$data=[])
    {
        #表默认值
        $data['like_count']=0;
        $data['dislike_count']=0;
        $data['report_count']=0;
        $data['pending_report_count']=0;
        $data['is_reported']=2;
        if(empty($data['client_ip'])){
            $data['client_ip']=get_client_ip();
        }

        $data['create_time']=date("Y-m-d H:i:s");
        $data['update_time']=date("Y-m-d H:i:s");
        
        $data['parent_id']=0;
        $type=$data['type'];
        $unique_id=$data['unique_id'];
        $people_id=$data['people_id'];
        $content=$data['content'];
        $parent_id=$data['parent_id'];
        $commentId=$this->commentAdd($type,$unique_id,$people_id, $content, $parent_id,$data);
        //添加用户信息
        $this->userService->addDate($request,$people_id);

        if($commentId){
            $commit_data=$this->model->where(['id'=>$commentId])->first();
            #整合一下数据
            $people_id=$commit_data['people_id'];
            $userData=$this->userService->update_user($people_id);
            $commit_data['people_nickname']=$userData['nickname'];
            $commit_data['people_avatar']=$userData['avatar'];
            $commit_data['images']=json_decode($commit_data['images'],true); 

            $this->success($commit_data);
        }else{
            $this->error();
        }
        
        
    }
   

    public  function commentAdd($type,$unique_id, $people_id, $content, $parent_id,$data=[])
    {
        $pythonInfo=[];
        switch ($type){
            case '1':

                $pythonInfo=$this->doubanpost->where(['unique_id'=>$unique_id])->first();
                $comment_count=$this->model->where(['unique_id'=>$unique_id])->count();
                break;
            case '2':
                $pythonInfo=$this->baoliaopost->where(['unique_id'=>$unique_id])->first();
                $comment_count=$this->model->where(['unique_id'=>$unique_id])->count();

                break;
            default:
        }
        $commentInfo = [];
        $commentInfo=$this->model->where(['id'=>$parent_id])->first();

        $commentId = 0;
        $unique_id = $pythonInfo['unique_id'] ?? 0;
        $publisherId = $pythonInfo['user_id'] ?? 0;
        $crumbs = [0];
        if ($commentInfo) {
            $parent_id = $commentInfo['id'] ?? 0;
            $insert['commented_people_id'] = $commentInfo['people_id'] ?? 0;
            $insert['parent_id'] = $parent_id;
            $crumbs = $this->getCrumbs($parent_id);
        }else{
            $insert['commented_people_id'] =0;
        }
        $insert['unique_id'] = $unique_id;
        $insert['people_id'] = $people_id;
        $insert['is_pubisher'] = $people_id == $publisherId ? 1 : 0;
        $insert['content'] = $content;
        $insert['status'] = 1;
        $insert['create_time'] = date("Y-m-d H:i:s");;
        $insert['crumbs'] = json_encode($crumbs);
        $result = array_merge($insert, $data);
        //dd($result);
        $commentId = $this->model->insertGetId($result);
        //统计评论次数
        $comment_count=$comment_count+1;
        switch ($type){

            case '1'://豆瓣
                $this->doubanpost->where(['unique_id'=>$unique_id])->update(['comment_count'=>$comment_count]);
                break;
            case '2'://爆料
                $this->baoliaopost->where(['unique_id'=>$unique_id])->update(['comment_count'=>$comment_count]);
                break;
            default:
        }

        return $commentId;
    }
    //二级评论添加2
    public function addDate2($request,$data=[])
    {
        
        #表默认值
        $data['like_count']=0;
        $data['dislike_count']=0;
        $data['report_count']=0;
        $data['pending_report_count']=0;
        $data['is_reported']=2;

        $data['create_time']=date("Y-m-d H:i:s");
        $data['update_time']=date("Y-m-d H:i:s");
        if(empty( $data['client_ip'])){
            $data['client_ip']=get_client_ip();
        }
        
        $type=$data['type'];
        $unique_id=$data['unique_id'];
        $people_id=$data['people_id'];
        $content=$data['content'];
        $parent_id=$data['parent_id'];
        $commentId=$this->commentAdd($type,$unique_id,$people_id, $content, $parent_id,$data);
        //添加用户信息
        $this->userService->addDate($request,$people_id);
        if($commentId){
            $commit_data=$this->model->where(['id'=>$commentId])->first();
            #整合一下数据
 /*           $people_id=$commit_data['people_id'];
            $userData=$this->userService->update_user($people_id);
            $commit_data['people_nickname']=$userData['nickname'];
            $commit_data['people_avatar']=$userData['avatar'];*/
            $commit_data['images']=json_decode($commit_data['images'],true); 

            $commented_people_id=$commit_data['commented_people_id'];
            $tohuto_msg=$this->tohuto_msg($people_id,$commented_people_id);
            if($tohuto_msg){
                $commit_data['people_nickname']=$tohuto_msg['people_nickname'];
                $commit_data['people_avatar']=$tohuto_msg['people_avatar'];
                $commit_data['people_msg']=$tohuto_msg['people_msg'];
                $commit_data['_people_msg']=$tohuto_msg['_people_msg'];
            }



            $this->success($commit_data);
        }else{
            $this->error();
        }
        
        
    }


    #更新评论点赞或者踩的次数
    public function updateLikesDislikes($comment_id)
    {
        $where=[
            'comment_id'=>$comment_id,
        ];

        $list=$this->commentvote->where($where)->select()->get()->toArray();
        //dd($list);
        $like_count=[];
        $dislike_count=[];
        foreach($list as $k=>$v){
            $vote_type=$v['vote_type'];
            switch ($vote_type) {
                case '1':#点赞
                    $like_count[]=$vote_type;
                    break;
                case '-1':#点踩
                    $dislike_count[]=$vote_type;
                    break;

                default:

            }

        }
        $like_count=count($like_count);
        $dislike_count=count($dislike_count);

        #更新 评论表 
        $hdata=[
            'like_count'=>$like_count,
            'dislike_count'=>$dislike_count,
        ];
        $this->model->where(['id'=>$comment_id])->update($hdata);
        //dd($like_count);


    }
}
